<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>FinData - 登录</title>
    <style>
        body {
            margin: 0;
            background: linear-gradient(135deg, #0a0a0a, #1a1a2e);
            font-family: 'Arial', sans-serif;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .login-container {
            width: 400px;
            background: rgba(18, 18, 18, 0.8);
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 0 30px rgba(138, 43, 226, 0.3);
        }
        
        .login-title {
            text-align: center;
            font-size: 2rem;
            margin-bottom: 30px;
            background: linear-gradient(90deg, #8a2be2, #00bfff);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }
        
        .input-group {
            margin-bottom: 25px;
        }
        
        .input-group label {
            display: block;
            margin-bottom: 8px;
            color: #e0e0e0;
        }
        
        .input-group input {
            width: 100%;
            padding: 12px;
            background: #121212;
            border: 1px solid #333;
            border-radius: 5px;
            color: #e0e0e0;
            font-size: 1rem;
        }
        
        .login-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(90deg, #8a2be2, #00bfff);
            border: none;
            border-radius: 5px;
            color: white;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .login-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(138, 43, 226, 0.4);
        }
        
        .auth-links {
            display: flex;
            justify-content: center;
            gap: 24px;
            margin-top: 30px;
        }
        
        .auth-link {
            color: #9d7cff;  /* 柔和的紫色 */
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 500;
            letter-spacing: 0.3px;
            transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            padding-bottom: 4px;
        }
        
        .auth-link:hover {
            color: #00e1ff;  /* 明亮的蓝色 */
        }
        
        .auth-link::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 0;
            height: 1px;
            background: linear-gradient(90deg, #9d7cff, #00e1ff);
            transition: width 0.3s ease;
        }
        
        .auth-link:hover::after {
            width: 100%;
        }
        
        .error-message {
            color: #ff6b6b;
            background-color: rgba(255, 107, 107, 0.1);
            border: 1px solid rgba(255, 107, 107, 0.3);
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 20px;
            display: none;
        }
        
        .success-message {
            color: #6bff6b;
            background-color: rgba(107, 255, 107, 0.1);
            border: 1px solid rgba(107, 255, 107, 0.3);
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 20px;
            display: none;
        }
        
        .home-link {
            position: fixed;
            top: 20px;
            left: 20px;
            display: flex;
            align-items: center;
            color: #e0e0e0;
            text-decoration: none;
            font-size: 0.9rem;
            padding: 8px 12px;
            background: rgba(18, 18, 18, 0.7);
            border-radius: 5px;
            transition: all 0.3s;
        }
        
        .home-link:hover {
            background: rgba(138, 43, 226, 0.3);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        .home-icon {
            margin-right: 5px;
            width: 16px;
            height: 16px;
        }
        
        /* 版权信息样式 */
        .copyright-container {
            background-color: rgba(18, 18, 18, 0.8);
            padding: 15px;
            margin-top: 30px;
            text-align: center;
            border-top: 1px solid #333;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
        }
        
        .copyright {
            font-size: 12px;
            color: #666;
            text-align: center;
        }
    </style>
</head>
<body>
    <a href="/blank" class="home-link">
        <svg class="home-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 9L12 2L21 9V20C21 20.5304 20.7893 21.0391 20.4142 21.4142C20.0391 21.7893 19.5304 22 19 22H5C4.46957 22 3.96086 21.7893 3.58579 21.4142C3.21071 21.0391 3 20.5304 3 20V9Z" stroke="#e0e0e0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M9 22V12H15V22" stroke="#e0e0e0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        返回主页
    </a>
    
    <div class="login-container">
        <h1 class="login-title">欢迎回到FinData</h1>
        <div id="error-message" class="error-message"></div>
        <div id="success-message" class="success-message"></div>
        <form id="loginForm">
            <div class="input-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="input-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required>
            </div>
            <button type="submit" class="login-btn">登录</button>
        </form>
        
        <!-- 账户封禁提示模态框 -->
        <div id="banModal" class="modal" style="display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.8); align-items: center; justify-content: center;">
            <div class="modal-content" style="background: linear-gradient(145deg, #151515, #1e1e1e); border-radius: 15px; max-width: 500px; margin: 0 auto; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); overflow: hidden; animation: fadeIn 0.4s; position: relative; border-left: 3px solid #dc3545;">
                <div class="modal-header" style="padding: 15px 20px; text-align: center; border-bottom: 1px solid #333; background: rgba(220, 53, 69, 0.1);">
                    <h3 style="margin: 0; color: #dc3545; font-weight: 600;">账户已被封禁</h3>
                </div>
                <div class="modal-body" style="padding: 20px 25px; display: flex; flex-direction: column; align-items: center;">
                    <div style="display: flex; align-items: center; margin-bottom: 20px;">
                        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" style="margin-right: 15px;">
                            <circle cx="12" cy="12" r="10" stroke="#dc3545" stroke-width="2"/>
                            <path d="M15 9L9 15" stroke="#dc3545" stroke-width="2" stroke-linecap="round"/>
                            <path d="M9 9L15 15" stroke="#dc3545" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                        <p id="banMessage" style="margin: 0; font-size: 16px; color: #e0e0e0;"></p>
                    </div>
                    <div style="background: rgba(220, 53, 69, 0.1); padding: 15px; border-radius: 8px; width: 100%; margin-bottom: 15px;">
                        <div style="margin-bottom: 10px;">
                            <span style="font-weight: 600; color: #aaa;">封禁原因:</span>
                            <p id="banReason" style="margin: 5px 0 0 0; color: #e0e0e0;"></p>
                        </div>
                    </div>
                    <p style="color: #aaa; font-size: 0.9rem; text-align: center; margin-bottom: 20px;">
                        如有疑问，请联系管理员获取帮助。
                    </p>
                </div>
                <div class="modal-footer" style="padding: 15px 20px; border-top: 1px solid #333; text-align: center;">
                    <button id="closeBanBtn" style="background: linear-gradient(90deg, #dc3545, #c82333); border: none; padding: 8px 25px; border-radius: 50px; color: white; cursor: pointer; transition: all 0.3s ease;">我知道了</button>
                </div>
            </div>
        </div>

        <script>
        // 检查URL参数是否包含成功消息
        window.onload = function() {
            console.log('登录页面加载完成');
            
            // 检查会话存储中是否有返回URL
            const returnUrl = sessionStorage.getItem('returnUrl');
            const testReturnUrl = sessionStorage.getItem('testReturnUrl');
            
            console.log('检测到会话存储中的returnUrl:', returnUrl);
            console.log('检测到会话存储中的testReturnUrl:', testReturnUrl);
            
            if (returnUrl || testReturnUrl) {
                // 显示通知，表明用户是从其他页面跳转来的
                const successElement = document.getElementById('success-message');
                successElement.textContent = '登录后将自动返回到之前的页面';
                successElement.style.display = 'block';
                
                // 3秒后自动隐藏成功消息
                setTimeout(() => {
                    successElement.style.display = 'none';
                }, 3000);
            }
            
            const urlParams = new URLSearchParams(window.location.search);
            const successMsg = urlParams.get('success');
            if (successMsg) {
                const successElement = document.getElementById('success-message');
                successElement.textContent = decodeURIComponent(successMsg);
                successElement.style.display = 'block';
                
                // 3秒后自动隐藏成功消息
                setTimeout(() => {
                    successElement.style.display = 'none';
                }, 3000);
            }
            
            // 初始化封禁模态框
            document.getElementById('closeBanBtn').addEventListener('click', function() {
                document.getElementById('banModal').style.display = 'none';
            });
        };
        
        document.getElementById('loginForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const errorElement = document.getElementById('error-message');
            
            // 隐藏之前可能显示的错误信息
            errorElement.style.display = 'none';
            
            const formData = new URLSearchParams();
            formData.append('username', username);
            formData.append('password', password);
            
            console.log('发送登录请求，数据：', { username, password: '******' });
            
            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Accept': 'application/json'
                    },
                    credentials: 'include'  // 必须包含这个选项
                });
                
                console.log('服务器响应状态:', response.status);
                const responseText = await response.text();
                console.log('服务器响应内容:', responseText);
                
                // 尝试解析JSON
                let result;
                try {
                    result = JSON.parse(responseText);
                } catch (jsonError) {
                    console.error('JSON解析错误:', jsonError);
                    errorElement.textContent = `响应不是有效的JSON格式: ${responseText}`;
                    errorElement.style.display = 'block';
                    return;
                }
                
                // 检查是否账户被封禁（403状态码）
                if (response.status === 403 && result.isBanned) {
                    console.log('账户被封禁，显示封禁提示');
                    
                    // 设置封禁信息
                    document.getElementById('banMessage').textContent = result.detail || '您的账户已被封禁，无法登录。';
                    document.getElementById('banReason').textContent = result.reason || '违反平台规则';
                    
                    // 显示封禁模态框
                    document.getElementById('banModal').style.display = 'flex';
                    return;
                } else if (response.ok) {
                    // 登录成功
                    if (result.message) {
                        const successElement = document.getElementById('success-message');
                        successElement.textContent = result.message;
                        successElement.style.display = 'block';
                    }
                    
                    // 检查本地存储是否有自选股票需要导入
                    const localFavorites = localStorage.getItem('favorites');
                    if (localFavorites) {
                        try {
                            const favorites = JSON.parse(localFavorites);
                            if (favorites && favorites.length > 0) {
                                console.log('检测到本地自选股票，准备导入到服务器', favorites);
                                
                                // 导入自选股票到服务器
                                await importLocalFavorites(favorites);
                                
                                // 提示用户自选股票已导入
                                const successElement = document.getElementById('success-message');
                                successElement.textContent = `登录成功，已导入${favorites.length}支自选股票`;
                                successElement.style.display = 'block';
                            }
                        } catch (error) {
                            console.error('导入自选股票失败:', error);
                        }
                    }
                    
                    // 处理跳转
                    // 依次检查returnUrl, testReturnUrl, 服务器返回的redirect
                    console.log('处理登录后跳转');
                    const returnUrl = sessionStorage.getItem('returnUrl');
                    const testReturnUrl = sessionStorage.getItem('testReturnUrl');
                    
                    console.log('返回URL检查: returnUrl=', returnUrl, ', testReturnUrl=', testReturnUrl);
                    
                    setTimeout(() => {
                        if (returnUrl) {
                            console.log('使用returnUrl跳转:', returnUrl);
                            sessionStorage.removeItem('returnUrl');
                            window.location.href = returnUrl;
                        } else if (testReturnUrl) {
                            console.log('使用testReturnUrl跳转:', testReturnUrl);
                            sessionStorage.removeItem('testReturnUrl');
                            window.location.href = testReturnUrl;
                        } else if (result.redirect) {
                            console.log('使用服务器提供的跳转:', result.redirect);
                            window.location.href = result.redirect;
                        } else {
                            console.log('没有返回URL，跳转到默认页面');
                            window.location.href = '/dashboard';
                        }
                    }, 500); // 添加短暂延迟，让用户看到成功消息
                } else {
                    // 登录失败，显示错误信息
                    errorElement.textContent = result.detail || '登录失败，请检查用户名和密码';
                    errorElement.style.display = 'block';
                }
            } catch (error) {
                console.error('请求出错:', error);
                errorElement.textContent = '网络请求失败，请稍后再试';
                errorElement.style.display = 'block';
            }
        });
        
        // 导入本地自选股票到服务器
        async function importLocalFavorites(favorites) {
            try {
                console.log('开始导入本地自选股票，数量:', favorites.length);
                
                // 依次添加每个本地自选股票
                for (const stock of favorites) {
                    try {
                        const response = await fetch('/api/add-favorite', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ 
                                stockCode: stock.code,
                                stockName: stock.name
                            }),
                            credentials: 'include'
                        });
                        
                        if (!response.ok) {
                            console.error('导入自选股票失败:', stock.code);
                        }
                    } catch (err) {
                        console.error('导入单个自选股票出错:', err);
                    }
                }
                
                // 导入完成后清空本地存储
                localStorage.removeItem('favorites');
                console.log('本地自选股票导入完成并清除本地存储');
                return true;
            } catch (error) {
                console.error('导入本地自选股票错误:', error);
                return false;
            }
        }
        </script>

        <div class="auth-links">
            <a href="/forgot-password" class="auth-link">忘记密码</a>
            <a href="/register" class="auth-link">立即注册</a>
        </div>
    </div>
    
    <!-- Debug信息面板 -->
    <div id="debugPanel" style="position: fixed; bottom: 10px; right: 10px; background: rgba(0,0,0,0.8); padding: 10px; border-radius: 5px; color: #e0e0e0; font-size: 12px; max-width: 300px; max-height: 200px; overflow: auto; z-index: 1000; display: none;">
        <div style="margin-bottom: 10px; font-weight: bold; color: #00bfff;">调试信息</div>
        <div id="debugInfo">加载中...</div>
        <div style="margin-top: 10px; display: flex; gap: 5px;">
            <button id="testReturnBtn" style="background: #8a2be2; color: white; border: none; padding: 3px 8px; border-radius: 3px; font-size: 12px;">测试返回</button>
            <button id="clearSessionBtn" style="background: #ff4757; color: white; border: none; padding: 3px 8px; border-radius: 3px; font-size: 12px;">清除会话</button>
            <button id="closeDebugBtn" style="background: #333; color: white; border: none; padding: 3px 8px; border-radius: 3px; font-size: 12px;">关闭</button>
        </div>
    </div>
    
    <script>
        // 按下Alt+D组合键显示调试面板
        document.addEventListener('keydown', function(e) {
            if (e.altKey && e.key === 'd') {
                const debugPanel = document.getElementById('debugPanel');
                debugPanel.style.display = debugPanel.style.display === 'none' ? 'block' : 'none';
                
                if (debugPanel.style.display === 'block') {
                    updateDebugInfo();
                }
            }
        });
        
        // 更新调试信息
        function updateDebugInfo() {
            const debugInfo = document.getElementById('debugInfo');
            const returnUrl = sessionStorage.getItem('returnUrl');
            const testReturnUrl = sessionStorage.getItem('testReturnUrl');
            
            let html = '<b>会话存储:</b><br>';
            html += `returnUrl: ${returnUrl || '未设置'}<br>`;
            html += `testReturnUrl: ${testReturnUrl || '未设置'}<br>`;
            html += '<br><b>本地存储:</b><br>';
            
            const favorites = localStorage.getItem('favorites');
            if (favorites) {
                try {
                    const parsedFavorites = JSON.parse(favorites);
                    html += `自选股票: ${parsedFavorites.length}个<br>`;
                } catch (e) {
                    html += `自选股票: 格式错误<br>`;
                }
            } else {
                html += `自选股票: 未设置<br>`;
            }
            
            debugInfo.innerHTML = html;
        }
        
        // 测试返回按钮
        document.getElementById('testReturnBtn').addEventListener('click', function() {
            const returnUrl = sessionStorage.getItem('returnUrl') || sessionStorage.getItem('testReturnUrl') || '/favorites';
            window.location.href = returnUrl;
        });
        
        // 清除会话按钮
        document.getElementById('clearSessionBtn').addEventListener('click', function() {
            sessionStorage.clear();
            updateDebugInfo();
            alert('会话已清除');
        });
        
        // 关闭调试面板
        document.getElementById('closeDebugBtn').addEventListener('click', function() {
            document.getElementById('debugPanel').style.display = 'none';
        });
    </script>
    
    <!-- 版权信息 -->
    <div class="copyright-container">
        <div class="copyright">
            © 2023-2024 FinData. All Rights Reserved. 保留所有权利。
        </div>
    </div>
</body>
</html>